package org.summer.lawyer.im;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.exception.ServiceException;
import org.summer.lawyer.im.config.ImConfig;
import org.summer.lawyer.im.dto.AccIdCreateDTO;
import org.summer.lawyer.im.dto.AccIdInfoDto;

import java.util.Map;

/**
 *
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ImService {

    private final ImConfig imConfig;

    private final String CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";

    /**
     * 创账号
     */
    public AccIdInfoDto userCreate(AccIdCreateDTO dto) {
        String api = "/user/create.action";
        Map<String, Object> paramMap= MapUtil.newConcurrentHashMap();
        paramMap.put("accid", dto.getAccid());
        paramMap.put("name", dto.getName());
        String resultJson = createRequest(api,paramMap);
        log.info("创建云信账号返回信息：{}",JSONUtil.toJsonStr(resultJson));
         if(StrUtil.isEmpty(resultJson)){
             throw new ServiceException("创建云信账号失败");
         }
         return JSONUtil.toBean(resultJson,AccIdInfoDto.class);
    }

    public String createRequest(String api, Map<String,Object> paramMap) {
        String appServer = imConfig.getAppServer();
        String appKey = imConfig.getAppKey();
        String appSecret = imConfig.getAppSecret();
        String noce = IdUtil.nanoId(12);
        String curTime = String.valueOf(DateUtil.currentSeconds());
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, noce, curTime);

        api = StrUtil.format("{}{}" , imConfig.getAppServer(), api);
        HttpRequest request = HttpUtil.createPost(api);
        request.header("Content-Type" , CONTENT_TYPE);
        request.header("AppKey" , appKey);
        request.header("Nonce" , noce);
        request.header("CurTime" , curTime);
        request.header("CheckSum" , checkSum);
        try {
            HttpResponse response = request.form(paramMap).execute();
            if(response.getStatus() == HttpStatus.HTTP_OK){
                JSONObject jsonObject = JSONUtil.parseObj(response.body());
                if(!"200".equals(jsonObject.getStr("code"))){
                    log.error("云信接口返回错误：{}", response.body());
                    return "";
                }
                return jsonObject.getStr("info");
            }
        }catch (Exception ex){
            log.error("调用云信接口“{}”发生错误，", ex.getMessage());
        }
        return "";
    }
}
